<template>
	<div>
		<h4>发表评论</h4>
		<hr />
		<textarea placeholder="请输入评论(最多120字)"maxlength="120" v-model="msg"></textarea>
		<mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>

		<div class="cmt-list">
			<div class="cmt-item" v-for="(item,i) in comment">
				<div class="cmt-title">第{{i+1}}楼&nbsp;&nbsp;用户：{{item.user_name}}</div>
				<div class="cmt-body">{{item.content}}</div>
			</div>
		</div>
	<mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
	</div>
</template>

<script>
	import {Toast} from 'mint-ui'
	export default({
		data(){
			return {
				msg:"",
				pageIndex:1,//默认展示第一页数据
				comment:[]
			}
		},
		created(){
			this.getComments()
		},
		methods:{
			getComments(){
				this.$http.get("http://localhost:3001/newscontent/"+this.id).then(result=>{
					if(result.body){
						var arr = result.body.comments;
						for(var i=0;i<arr.length;i++){
							if(arr[i].pageIndex === this.pageIndex)
							{
							this.comment = this.comment.concat(arr[i])
							}
						}
						//每当获取评论新数据的时候，要用老数据拼接上新数据
					} 
					else{
						Toast('获取评论失败')
					}
				})
			},
			getMore(){//加载更多
				this.pageIndex++
				this.getComments()
			},
			postComment(){
				//参数1：url地址
				//参数2：提价的数据对象（content:msg）
				//参数3:emulateJSON
			
				if(this.msg.trim().length===0){
				return Toast("评论内容不能为空");
				}
				
				this.$http.get("http://localhost:3001/newscontent?newsid="+this.id,{"content":this.msg.trim()}).then(result=>{
					if(result.body){
						//1.拼接评论对象
				var cmt = {"uewsid":this.id,"pageIndex":this.pageIndex,"user_name":"匿名用户","add_time":Date.now(),"content":this.msg.trim()}
					}
					this.comment.unshift(cmt)
					this.msg=""
				})	
			}
		},
		props:["id"]
	})
</script>

<style>
	textarea{
		margin: 0;
	}
	.mint-button--large{
		margin-bottom: 2px;
	}
	.mint-button{
		height: 38px;
	}
	.cmt-item{
		font-size: 14px;
	}
	.cmt-title{
		line-height: 30px;
		background:#CCCCCC;
		}
	.cmt-body{
		padding: 4px;
		border: 1px solid #CCCCCC;
		margin-bottom: 2px;;
		color: #333333;
		}
</style>
